package com.wxmit.module.system.web.monitor;

import cn.dev33.satoken.session.SaSession;
import cn.dev33.satoken.stp.StpUtil;
import com.wxmit.base.domain.ApiResult;
import com.wxmit.base.util.DateUtils;
import com.wxmit.framework.satoken.core.util.StpUserUtil;
import com.wxmit.module.system.domain.dto.OnlineUserDTO;
import com.wxmit.system.base.core.ShushanBaseController;
import com.wxmit.system.base.core.ShushanPage;
import com.wxmit.system.base.domain.PageDTO;
import com.wxmit.system.domain.LoginUser;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.stream.Collectors;

/**
 * OnlineController
 *
 * @author huangxiong
 * @version V1.0
 * @date 2022/12/9 17:24
 */
@RestController
@RequestMapping("/monitor/online")
public class OnlineController {


    @PostMapping("/list")
    public List<OnlineUserDTO> list(@RequestBody PageDTO pageDto){
        ShushanPage page = pageDto.getPage();
        int size = longToInt(page.getSize());
        List<String> searchSessionIds = StpUtil.searchSessionId("", (longToInt(page.getCurrent()) - 1) * size , size, true);

        List<OnlineUserDTO> onlineUsers = searchSessionIds.stream().map(it -> {
            SaSession session = StpUtil.getSessionBySessionId(it);
            LoginUser loginUser = (LoginUser) session.get(StpUserUtil.LOGIN_USER_NAME);
            return new OnlineUserDTO().setSessionId(it).setLoginTime(DateUtils.date(session.getCreateTime())).setByLoginUser(loginUser);
        }).collect(Collectors.toList());

        return onlineUsers;
    }

    @DeleteMapping("/{id}")
    public ApiResult retreat(@PathVariable("id") Long userId){
        Assert.isTrue(!StpUserUtil.isAdmin(userId),"不可操作admin！");
        StpUtil.kickout(userId);
        return ApiResult.success();
    }

    private int longToInt(long val){
        return Long.valueOf(val).intValue();
    }
}
